package com.hf.security

import com.hf.constant.OrderLunchConst
import com.hf.date.DateUtils
import com.hf.order.OrderPeriodType

class SystemConfigService {

	static final String NAME_IS_RAIN_DAY = "IS_RAIN_DAY"
	static final String VALUE_IS_RAIN_DAY = "false"

	static final String NAME_BILL_DAY_OF_PERIOD = "BILL_DAY_OF_PERIOD"
	static final String VALUE_BILL_DAY_OF_PERIOD = "1"

	static final String NAME_ = ""
	static final String VALUE_ = ""

	//	static final String NAME_ = ""
	//	static final String VALUE_ = ""

	void init() {
		getIsRainDay()
		getBillDayOfPeriod()
	}

	// IS_RAIN_DAY
	boolean getIsRainDay() {
		SystemConfig systemConfig = getSystemConfig(NAME_IS_RAIN_DAY, VALUE_IS_RAIN_DAY)
		return systemConfig.value.toBoolean()
	}

	void setDefaultValueIsRainDay() {
		setSystemConfig(NAME_IS_RAIN_DAY, VALUE_IS_RAIN_DAY)
	}

	void setRainDay(boolean value) {
		setSystemConfig(NAME_IS_RAIN_DAY, String.valueOf(value))
	}

	// BILL_DAY_OF_PERIOD
	int getBillDayOfPeriod() {
		SystemConfig systemConfig = getSystemConfig(NAME_BILL_DAY_OF_PERIOD, VALUE_BILL_DAY_OF_PERIOD)
		return systemConfig.value.toInteger()
	}

	void setBillDayOfNextPeriod() {
		String value
		if (OrderLunchConst.curOrderPeriodType == OrderPeriodType.month) {
			value = DateUtils.getJodaLastWorkDayInMonth(DateUtils.getDayInNextMonth()).dayOfMonth.toString() // VALUE_BILL_DAY_OF_PERIOD
		} else if (OrderLunchConst.curOrderPeriodType == OrderPeriodType.week) {
			value = "5"
		} else {
			throw new IllegalArgumentException()
		}
		setSystemConfig(NAME_BILL_DAY_OF_PERIOD, value)
	}
	
	void setBillDayOfPeriod(int value) {
		setSystemConfig(NAME_BILL_DAY_OF_PERIOD, String.valueOf(value))
	}

	boolean isBillDayOfPeriod() {
		return DateUtils.getDayOfPeriod() == getBillDayOfPeriod()
	}

	// set get
	void setSystemConfig(String name, String value) {
		SystemConfig systemConfig = SystemConfig.findByName(name)
		if (systemConfig) {
			systemConfig.value = value
			systemConfig.save()
		}
	}

	SystemConfig getSystemConfig(String name, String value) {
		SystemConfig systemConfig = SystemConfig.findByName(name)
		if (!systemConfig) {
			systemConfig = new SystemConfig(name : name, value : value)
			systemConfig.save()
		}

		return systemConfig
	}
}
